package common.adapters;

import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.CursorAdapter;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import common.managers.IImageManager;

public abstract class AbstractCursorAdapter extends CursorAdapter {

	private IImageManager imageManager;
	private int[] viewId;
	private String[] columnNames;

	public AbstractCursorAdapter(Context context, Cursor c, IImageManager imageManager, int[] viewId,
			String[] columnNames) {
		super(context, c, true);
		this.imageManager = imageManager;
		this.viewId = viewId;
		this.columnNames = columnNames;
	}

	@Override
	public void bindView(View convertView, Context context, Cursor cursor) {
		for (int i = 0; i < viewId.length; i++) {
			View view = convertView.findViewById(viewId[i]);
			if (view instanceof TextView) {
				TextView textView = (TextView) view;
				String data = cursor.getString(cursor.getColumnIndex(columnNames[i]));
				if (!TextUtils.isEmpty(data)) {
					textView.setVisibility(View.VISIBLE);
					textView.setText(data);
				} else {
					textView.setVisibility(View.GONE);
				}
			}

			if (view instanceof ImageView) {
				ImageView imageView = (ImageView) view;
				String data = cursor.getString(cursor.getColumnIndex(columnNames[i]));
				if (!TextUtils.isEmpty(data)) {
					imageView.setVisibility(View.VISIBLE);
					imageManager.loadImage(data, imageView);
				} else {
					setImageNull(imageView);
				}
			}
		}
	}

	

	@Override
	public View newView(Context context, Cursor cursor, ViewGroup viewgroup) {
		return View.inflate(context, getLayoutAdapterId(), null);
	}

	public abstract int getLayoutAdapterId();
	public abstract void setImageNull(ImageView imageView);

}
